{% extends "base.html" %}

{% block title %}高级数据分析{% endblock %}

{% block head %}
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.0/echarts.min.js"></script>
<style>
.chart-container {
    height: 300px;
    margin-bottom: 20px;
}
.kpi-card {
    text-align: center;
    padding: 20px;
}
.kpi-value {
    font-size: 2.5rem;
    font-weight: bold;
}
.kpi-label {
    font-size: 1rem;
    color: #6c757d;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <h2 class="mb-4"><i class="fas fa-chart-pie me-2"></i>高级数据分析</h2>
    
    <!-- 转化漏斗 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">用户行为转化漏斗</h5>
                </div>
                <div class="card-body">
                    <div id="funnel-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 客户留存数据 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white text-center">
                    <h5 class="mb-0">客户复购率</h5>
                </div>
                <div class="card-body kpi-card">
                    <div id="retention-rate" class="kpi-value">-</div>
                    <div class="kpi-label">客户复购比例</div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-header bg-info text-white text-center">
                    <h5 class="mb-0">复购客户数</h5>
                </div>
                <div class="card-body kpi-card">
                    <div id="repeat-users" class="kpi-value">-</div>
                    <div class="kpi-label">两次以上订单客户</div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-header bg-warning text-white text-center">
                    <h5 class="mb-0">总客户数</h5>
                </div>
                <div class="card-body kpi-card">
                    <div id="total-users" class="kpi-value">-</div>
                    <div class="kpi-label">总下单用户</div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-header bg-danger text-white text-center">
                    <h5 class="mb-0">近30天新客户</h5>
                </div>
                <div class="card-body kpi-card">
                    <div id="new-users" class="kpi-value">-</div>
                    <div class="kpi-label">最近30天新用户</div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 类别分析 -->
    <div class="row">
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-secondary text-white">
                    <h5 class="mb-0">类别销售比例</h5>
                </div>
                <div class="card-body">
                    <div id="category-pie" class="chart-container"></div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-dark text-white">
                    <h5 class="mb-0">类别订单数量</h5>
                </div>
                <div class="card-body">
                    <div id="category-bar" class="chart-container"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 初始化图表
const funnelChart = echarts.init(document.getElementById('funnel-chart'));
const categoryPie = echarts.init(document.getElementById('category-pie'));
const categoryBar = echarts.init(document.getElementById('category-bar'));

// 加载转化漏斗数据
fetch('/analytics/api/conversion_funnel')
    .then(response => response.json())
    .then(data => {
        funnelChart.setOption({
            title: {
                text: '用户行为转化漏斗',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b} : {c} ({d}%)'
            },
            legend: {
                data: ['浏览', '加购', '购买'],
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '转化漏斗',
                    type: 'funnel',
                    left: '10%',
                    top: 60,
                    bottom: 60,
                    width: '80%',
                    min: 0,
                    max: data.view,
                    minSize: '0%',
                    maxSize: '100%',
                    sort: 'descending',
                    gap: 2,
                    label: {
                        show: true,
                        position: 'inside'
                    },
                    labelLine: {
                        length: 10,
                        lineStyle: {
                            width: 1,
                            type: 'solid'
                        }
                    },
                    itemStyle: {
                        borderColor: '#fff',
                        borderWidth: 1
                    },
                    emphasis: {
                        label: {
                            fontSize: 20
                        }
                    },
                    data: [
                        {value: data.view, name: '浏览', itemStyle: {color: '#5470c6'}},
                        {value: data.add_cart, name: '加购', itemStyle: {color: '#91cc75'}},
                        {value: data.purchase, name: '购买', itemStyle: {color: '#ee6666'}}
                    ]
                }
            ]
        });
        
        // 在图表下方添加转化率说明
        const rateInfoDiv = document.createElement('div');
        rateInfoDiv.className = 'text-center mt-3';
        rateInfoDiv.innerHTML = `
            <div class="row">
                <div class="col-md-4">
                    <div class="alert alert-info">
                        浏览到加购转化率: <strong>${data.view_to_cart_rate.toFixed(2)}%</strong>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="alert alert-success">
                        加购到购买转化率: <strong>${data.cart_to_purchase_rate.toFixed(2)}%</strong>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="alert alert-danger">
                        浏览到购买转化率: <strong>${data.view_to_purchase_rate.toFixed(2)}%</strong>
                    </div>
                </div>
            </div>
        `;
        document.getElementById('funnel-chart').parentNode.appendChild(rateInfoDiv);
    })
    .catch(error => console.error('Error loading funnel data:', error));

// 加载客户留存数据
fetch('/analytics/api/customer_retention')
    .then(response => response.json())
    .then(data => {
        document.getElementById('retention-rate').innerText = data.retention_rate.toFixed(2) + '%';
        document.getElementById('repeat-users').innerText = data.repeat_users;
        document.getElementById('total-users').innerText = data.total_users;
        document.getElementById('new-users').innerText = data.new_users_30d;
    })
    .catch(error => console.error('Error loading retention data:', error));

// 加载类别分析数据
fetch('/analytics/api/category_analysis')
    .then(response => response.json())
    .then(data => {
        // 类别饼图
        categoryPie.setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 10,
                data: data.map(item => item.category)
            },
            series: [
                {
                    name: '销售额',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 16,
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: data.map(item => ({
                        value: item.total_sales,
                        name: item.category
                    }))
                }
            ]
        });
        
        // 类别柱状图
        categoryBar.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'category',
                data: data.map(item => item.category),
                axisLabel: {
                    interval: 0,
                    rotate: 30
                }
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '订单数',
                    type: 'bar',
                    data: data.map(item => item.order_count)
                }
            ]
        });
    })
    .catch(error => console.error('Error loading category data:', error));

// 图表响应式调整
window.addEventListener('resize', () => {
    funnelChart.resize();
    categoryPie.resize();
    categoryBar.resize();
});
</script>
{% endblock %}
